﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
using System.Web.UI;

namespace DCTLib.Common
{
    public class URLHelper
    {
          #region Properties

        /// <summary>
        /// This function returns the Application path, like http://localhost/, 
        /// or if the project is running in a virtual directory it returns the Application path of the virtual directory, like http://localhost/Website/.
        /// </summary>
        public static string RootURL
        {
            get
            {
                string Port = Request.ServerVariables["SERVER_PORT"];

                if (Port == null || Port == "80" || Port == "443")
                    Port = "";
                else
                    Port = ":" + Port;
                string Protocol = Request.ServerVariables["SERVER_PORT_SECURE"];
                if (Protocol == null || Protocol == "0")
                    Protocol = "http://";
                else
                    Protocol = "https://";

                // *** Figure out the base Url which points at the application's root
                string root = Protocol + Request.ServerVariables["SERVER_NAME"] + Port + ApplicationPath;
                return root.EndsWith("/") ? root : root + "/";
            }
        }

        public static string ApplicationPath
        {
            get
            {
                return System.Web.HttpContext.Current.Request.ApplicationPath;
            }
        }

        /// <summary>
        /// This function returns the Mapped path, like "C:\Hosting\Website\"
        /// </summary>
        public static string PhysicalApplicationPath
        {
            get
            {
                string app_path = ApplicationPath.ToLower();
                if (app_path == "/")      //a site
                    app_path = "/";
                else if (!app_path.EndsWith(@"/")) //a virtual
                    app_path += @"/";

                string it = Server.MapPath(app_path);
                if (!it.EndsWith(@"\"))
                    it += @"\";
                return it;
            }
        }

        #region Private
        private static HttpRequest Request
        {
            get
            {
                return HttpContext.Current.Request;
            }
        }

        private static HttpServerUtility Server
        {
            get
            {
                return HttpContext.Current.Server;
            }
        }
        #endregion
        #endregion

        #region Methods
        public static string GetAbsoluteURL(string relativeUrl)
        {
            if (string.IsNullOrEmpty(relativeUrl))
            {
                return RootURL;
            }
            else
            {
                Page page = (Page)HttpContext.Current.Handler;
                relativeUrl = page.ResolveUrl(relativeUrl).Replace("//", "/");
                while (relativeUrl.StartsWith("/"))
                {
                    relativeUrl = relativeUrl.Substring(1);
                }

                return RootURL + relativeUrl;
            }
        }

        public static string GetPhysicalPath(string relativeUrl)
        {
            if (string.IsNullOrEmpty(relativeUrl))
            {
                return PhysicalApplicationPath;
            }

            return Server.MapPath(GetAbsoluteURL(relativeUrl));
        }

        public static String ConvertRelativeURLToAbsolute(String text, String absoluteUrl)
        {
            if (!absoluteUrl.EndsWith("/"))
                absoluteUrl = absoluteUrl + "/";

            // Replace for pattern href="..."
            String value = Regex.Replace(text,
                "<(.*?)(src|href)=\"(?!http)(.*?)\"(.*?)>",
                "<$1$2=\"" + absoluteUrl + "$3\"$4>",
                RegexOptions.IgnoreCase | RegexOptions.Multiline);

            // Now just make sure that there isn't a // because if
            // the original relative path started with a / then the
            // replacement above would create a //.
            text = value.Replace(absoluteUrl + "/", absoluteUrl);

            // Replace for pattern href='...'
            value = Regex.Replace(text,
                "<(.*?)(src|href)='(?!http)(.*?)'(.*?)>",
                "<$1$2='" + absoluteUrl + "$3'$4>",
                RegexOptions.IgnoreCase | RegexOptions.Multiline);

            return value.Replace(absoluteUrl + "/", absoluteUrl);
        }

        public static string ExtractDomainName(string url)
        {
            if (url.Contains(@"://"))
                url = url.Split(new string[] { "://" }, 2, StringSplitOptions.None)[1];

            return url.Split('/')[0];
        }
        #endregion
	}

    public class AdvancedUri : Uri
    {
        private NameValueCollection request = new NameValueCollection();

        public NameValueCollection Request
        {
            get { return request; }
            set { request = value; }
        }

        public AdvancedUri(string url)
            : base(url)
        {
            string[] paramPairs = StringHelper.Split(this.Query, "&");
            string[] temp = new string[] { };
            for (int i = 0; i < paramPairs.Length; i++)
            {
                temp = StringHelper.Split(paramPairs[i], "=");
                if (i == 0)
                {
                    // Eliminate "?" character.
                    request.Add(temp[0].Substring(1), HttpUtility.UrlDecode(temp[1]));
                }
                else
                {
                    request.Add(temp[0], HttpUtility.UrlDecode(temp[1]));
                }
            }
        }
    }
}

